package exo1;


public class Pile implements Checked {
	
	protected final int MAX_TAILLE;
	protected int []tab;
	protected int index=0;
	protected int lock=0;
	public Pile() {
		this(10);
	}
	
	public Pile(int i) {
		MAX_TAILLE=i;
		tab=new int [MAX_TAILLE];
	}

	public void push(int i) {
		invariant();
		assert !isFull():"la pile est pliene,impossible d'empiler !!";
		tab[index]=i;
		index++;
		invariant();
	}

	public int pop() { invariant();
		assert !isEmpty():"impossible de depiler une pile vide";
		try{
			index--;
			int res= tab[index];
			return res;
		}finally{
			invariant();
		}
		
	}
	public int peek(){ invariant();
		assert !isEmpty():"impossible de retourner le sommet  une pile vide";
		try{
			return tab[index-1];
		}finally{
			invariant();
		}
	}
	public boolean isFull() {
		return (index==MAX_TAILLE);
	}

	public boolean isEmpty() {
		return (index==0);
	}
	
	public void invariant(){
		try{
			if(lock++!=0)return;
			assert index<=MAX_TAILLE:"index plus grande que la taille de tableau";
			assert index>=0:"index est négative";
		}finally{
			--lock;
		}
	}
	@Override
	public String toString() {
		String s="[";
		int i=0;
		for(i=0;i<index-1;i++){
			s+=tab[i]+",";
		}
		if(index!=0)
		s+=tab[i];
		return s+"]";
	}

	public static void main(String[] args) {
		try { // vérification du test d'assertion
			assert false;
			throw new RuntimeException("JVM option '-ea'");
			}catch (AssertionError e){}
		
			Pile pile=new Pile(2);
			assert"[]".equals(pile.toString()):pile;
			
			assert pile.isEmpty():"pile est vide";
			assert !pile.isFull():"Pile est pliene";
			pile.push(4);
			assert"[4]".equals(pile.toString()):pile;
			assert !pile.isEmpty():"pile est vide";
			pile.pop();
			assert"[]".equals(pile.toString()):pile;
			assert !pile.isFull():"pile est pliene";
			pile.push(8);
			pile.push(9);
			System.out.println(pile);
			assert pile.isFull():"Pile est Pliene";
			pile.peek();
			assert pile.toString().equals("[8,9]"):pile;
			System.out.println("Test unitaire validé");
	}

}